<template>
  <div>
    <header class="headerCtn flexJuconSpBeAliCenter">
      <div class="title">商品列表</div>
      <el-space>
        <!-- <div>所选商品数：0</div> -->
        <!-- <el-button type="primary">打印所选商品</el-button> -->
        <el-button type="primary" @click="goPage">进入所选任务</el-button>
      </el-space>
    </header>
    <div class="mainCtn" v-loading="loading">
      <div class="leftSide">
        <div v-for="item in firstGroup" :key="item.FID" @click="sideClick(item)">
          <div :class="{ item: true, active: item.FID === leftActive }">
            <el-icon
              @click.stop="clickAll(item, false)"
              v-if="item.isAll"
              style="margin-right: 10px"
              ><CircleCheckFilled
            /></el-icon>
            <div v-else class="cricle" @click="clickAll(item, true)"></div>
            {{ item.FNAME }}
          </div>
        </div>
      </div>
      <div class="rightContent">
        <el-collapse>
          <el-collapse-item :name="item.FID" v-for="(item, index) in secondGroup" :key="index">
            <template #title>
              <div @click.stop>
                <el-checkbox
                  v-model="item.checkAll"
                  :indeterminate="item.isIndeterminate"
                  @change="handleCheckAllChange(item)"
                  >{{ item.FNAME }}</el-checkbox
                >
              </div>
            </template>
            <el-checkbox-group
              v-model="item.checkedCities"
              @change="handleCheckedCitiesChange(item)"
            >
              <el-checkbox
                v-for="i in item.children"
                :key="i.FNumber"
                class="checkBox"
                :label="i"
                >{{ i.FName }}</el-checkbox
              >
            </el-checkbox-group>
          </el-collapse-item>
        </el-collapse>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref, watch } from 'vue'
import { queryGroupInfo } from '../api/home'
import { useRouter } from 'vue-router'
import { useGoodsStore } from '@/stores/goods'
import { ElMessage } from 'element-plus'
const router = useRouter()
const firstGroup = ref<GoodsTypes.firstGround[]>([])
const secondGroup = ref<GoodsTypes.secondGround[]>([])
const queryType = ref('')
const leftActive = ref('')
const loading = ref(false)
watch(
  () => router.currentRoute.value,
  (toPath) => {
    queryType.value = toPath.query.type as string
  },
  { immediate: true, deep: true }
)
const getInfo = async () => {
  // 一级分类查询
  const res: any = await queryGroupInfo({
    formid: 'SAL_MATERIALGROUP',
    data: {
      FieldKeys: 'FID,FPARENTID,FNAME',
      FilterString: [
        {
          Left: '(',
          FieldName: 'FPARENTID',
          Compare: '=',
          Value: 0,
          Right: ')',
          Logic: 'AND'
        }
      ],
      OrderString: '',
      TopRowCount: 0,
      StartRow: 0,
      Limit: 2000,
      SubSystemId: '',
      formid: 'SAL_MATERIALGROUP'
    }
  })
  const firstGroundArr: GoodsTypes.firstGround[] = []
  for (let index = 0; index < res.length; index++) {
    // 二级
    const res1: any = await queryGroupInfo({
      formid: 'SAL_MATERIALGROUP',
      data: {
        FieldKeys: 'FID,FPARENTID,FNAME',
        FilterString: [
          {
            Left: '(',
            FieldName: 'FPARENTID',
            Compare: '=',
            Value: res[index][0],
            Right: ')',
            Logic: 'AND'
          }
        ],
        OrderString: '',
        TopRowCount: 0,
        StartRow: 0,
        Limit: 2000,
        SubSystemId: '',
        formid: 'SAL_MATERIALGROUP'
      }
    })
    const secondGroundArr: GoodsTypes.secondGround[] = []
    for (let index1 = 0; index1 < res1.length; index1++) {
      // 获取商品
      const res2: any = await queryGroupInfo({
        formid: 'BD_MATERIAL',
        data: {
          FieldKeys: 'FName,FNumber',
          FilterString: [
            {
              Left: '(',
              FieldName: 'FMaterialGroup',
              Compare: '=',
              Value: res1[index1][0],
              Right: ')',
              Logic: 'AND'
            }
          ],
          OrderString: '',
          TopRowCount: 0,
          StartRow: 0,
          Limit: 2000,
          SubSystemId: '',
          formid: 'BD_MATERIAL'
        }
      })
      const goodsInfoArr: GoodsTypes.goodsInfo[] = []
      res2.forEach((j: string[]) => {
        let goodsObj = {
          FName: j[0],
          FNumber: j[1]
        }
        goodsInfoArr.push(goodsObj)
      })
      let secondObj = {
        FID: res1[index1][0],
        FPARENTID: res1[index1][1],
        FNAME: res1[index1][2],
        checkAll: false,
        isIndeterminate: false,
        checkedCities: [],
        children: goodsInfoArr
      }
      secondGroundArr.push(secondObj)
    }

    let firstObj = {
      FID: res[index][0],
      FPARENTID: res[index][1],
      FNAME: res[index][2],
      isAll: false,
      children: secondGroundArr
    }
    firstGroundArr.push(firstObj)
  }

  return firstGroundArr
}
onMounted(async () => {
  loading.value = true
  const firstGroundArr: GoodsTypes.firstGround[] = await getInfo()
  firstGroup.value = firstGroundArr

  leftActive.value = firstGroundArr[0]?.FID
  secondGroup.value = firstGroundArr[0]?.children
  loading.value = false
})
// 左侧点击
const sideClick = async (item: GoodsTypes.firstGround) => {
  if (leftActive.value === item.FID) {
    return
  }
  secondGroup.value = item.children
  leftActive.value = item.FID
}
// 全选
const handleCheckAllChange = (val: GoodsTypes.secondGround) => {
  if (val.checkedCities.length != val.children.length) {
    val.checkedCities = val ? val.children : []
  } else {
    val.checkedCities = []
  }
  val.isIndeterminate = false
}
// 单个点击
const handleCheckedCitiesChange = (value: GoodsTypes.secondGround) => {
  const checkedCount = value.checkedCities.length
  value.checkAll = checkedCount === value.children.length
  value.isIndeterminate = checkedCount > 0 && checkedCount < value.children.length
}
const clickAll = (item: GoodsTypes.firstGround, flag: boolean) => {
  loading.value = true
  setTimeout(() => {
    loading.value = false
  }, 1000)
  item.isAll = flag
  if (flag) {
    item.children.forEach((i) => {
      i.checkedCities = i.children
      i.isIndeterminate = true
    })
  } else {
    item.children.forEach((i) => {
      i.checkedCities = []
      i.isIndeterminate = false
    })
  }
}
const goPage = () => {
  const arr = []
  firstGroup.value.forEach((item) => {
    item.children.forEach((child) => {
      child.checkedCities.forEach((checked) => {
        arr.push(checked)
      })
    })
  })
  if (arr.length <= 0) {
    return ElMessage({
      type: 'warning',
      message: '请选择任务'
    })
  }
  useGoodsStore().goodsInfo = firstGroup.value
  console.log(secondGroup.value)
  router.push(`weightedGoods?type=${queryType.value}`)
}
</script>

<style scoped lang="less">
.headerCtn {
  padding: 20px;
  .title {
    font-size: 24px;
    font-family:
      PingFangSC,
      PingFang SC;
    font-weight: 500;
    color: #000000;
    line-height: 33px;
  }
}

.item {
  width: 184px;
  border-radius: 8px;
  margin-bottom: 12px;
  font-size: 18px;
  color: #8994b6;
  display: flex;
  align-items: center;
  padding: 15px;
  cursor: default;
}
.active {
  background: linear-gradient(90deg, #4e86ff 0%, #4a60fe 100%);
  color: #fff;
}
.cricle {
  width: 18px;
  height: 18px;
  border: 1px solid #ffffff;
  border-radius: 50%;
  margin-right: 15px;
}
.el-collapse {
  border-top: none;
}

:deep(.el-collapse-item__header) {
  background: #f3f4f9;
  border-radius: 8px;
  margin-bottom: 10px;
  padding: 0 10px;
}
.checkBox {
  min-width: 330px;
  border-radius: 8px 0px 0px 8px;
  border: 1px solid #ebebeb;
  padding: 10px 20px;
  margin-bottom: 10px;
}
</style>
